package com.alennus.blog.controller;

import com.alennus.blog.config.shiro.ShiroUtils;
import com.alennus.blog.domain.Account;
import com.alennus.blog.repository.AccountRepository;
import com.alennus.blog.response.WebApiResponse;
import com.alennus.blog.service.AccountRoleService;
import com.alennus.blog.service.AccountService;
import com.alennus.blog.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by pactera on 2018/5/14.
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    public AccountService accountService;

    @Autowired
    public AccountRoleService accountRoleService;


    @RequestMapping("/account")
    public String work(){
        Account account = new Account();
        account.setAccount("alennus");
        account.setPassword("123456");
        account.setPassword(ShiroUtils.sha256(account.getPassword(), account.getAccount()));
        accountService.saveOrUpdate(account);
        return "index";
    }

    @PostMapping("/register")
    public WebApiResponse<Account> register(@Valid Account account){
        return WebApiResponse.success(accountService.saveOrUpdate(account));
    }

    @GetMapping()
    public WebApiResponse<Page<Account>> accounts(Account account,Pageable pageable){
        return WebApiResponse.success(accountService.findAccount(account,pageable));
    }

    @PostMapping("/saveOrUpdate")
    public WebApiResponse<Account> save(@RequestBody Account account){
        String id = account.getId();
        if(StringUtils.isEmpty(id)){
            account.setPassword(ShiroUtils.sha256(account.getPassword(), account.getAccount()));
            account.setCreatedDate(DateUtils.getCurrentDatetime());
            account.setUpdateDate(DateUtils.getCurrentDatetime());
        }else{
            Account passAccount = accountService.findByID(id);
            account.setCreatedDate(account.getCreatedDate());
            account.setPassword(passAccount.getPassword());
            account.setUpdateDate(DateUtils.getCurrentDatetime());
        }
        return WebApiResponse.success(accountService.saveOrUpdate(account));
    }

    @PostMapping("/delete")
    public WebApiResponse<Account> delete(@RequestBody  List<Account> accounts){
        accountService.delete(accounts);
        return WebApiResponse.success();
    }

}
